<?php
namespace app\api\model;

use think\Model;
use think\exception\ValidateException;


// 订单总表
class Order extends Model
{
    protected $name = 'order';
    protected $autoWriteTimestamp = true;

    // 0:立即单, 1:预约单
    const APPOINT_TYPE_NOW = 0;
    const APPOINT_TYPE_WAIT = 1;

    public static function getAppointTypeStr()
    {
        return [
            self::APPOINT_TYPE_NOW => '立即单',
            self::APPOINT_TYPE_WAIT => '预约单',
        ];
    }
    
    // 第三方平台类型
    const APP_TYPE_SS = 1;
    const APP_TYPE_DD = 2;
    const APP_TYPE_FN = 3;

    public static function getAppTypeStr()
    {
        return [
            self::APP_TYPE_SS => '闪送',
            self::APP_TYPE_DD => '达达',
            self::APP_TYPE_FN => '蜂鸟',
        ];
    }

    // 订单状态
    const STATUS_ORDER_DISPATCH = 20;
    const STATUS_ORDER_PICKUPING = 30;
    const STATUS_ORDER_DELIVERY = 40;
    const STATUS_ORDER_COMPLETED = 50;
    const STATUS_ORDER_CANCELLED = 60;
    const STATUS_RIDERARRIVE = 100;
    const STATUS_DISPATCH_APPEND = 101;
    const STATUS_DELIVERY_BACK = 102;
    const STATUS_DELIVERY_BACK_COMPLETED = 103;
    const STATUS_AFTERSALE_BACK = 104;
    const STATUS_ADD_ORDER_FAIL = 105;

    public static function getStatusStr()
    {
        return [
            self::STATUS_ORDER_DISPATCH => '派单中',
            self::STATUS_ORDER_PICKUPING => '待取货',
            self::STATUS_ORDER_DELIVERY => '配送中',
            self::STATUS_ORDER_COMPLETED => '已完成',
            self::STATUS_ORDER_CANCELLED => '已取消',
            self::STATUS_RIDERARRIVE => '骑士到店',
            self::STATUS_DISPATCH_APPEND => '已追加待接单',
            self::STATUS_DELIVERY_BACK => '妥投异常之物品返回中',
            self::STATUS_DELIVERY_BACK_COMPLETED => '妥投异常之物品返回完成',
            self::STATUS_AFTERSALE_BACK => '售后取件单送达门店',
            self::STATUS_ADD_ORDER_FAIL => '创建达达运单失败',
        ];
    }

    //达达订单状态(待接单＝1,待取货＝2,骑士到店=100,配送中＝3,已完成＝4,已取消＝5, 已追加待接单=8,妥投异常之物品返回中=9, 妥投异常之物品返回完成=10, 售后取件单送达门店=6, 创建达达运单失败=1000）
    const DADA_STATUS_DISPATCH = 1;
    const DADA_STATUS_PICKUPING = 2;
    const DADA_STATUS_RIDERARRIVE = 100;
    const DADA_STATUS_DELIVERY = 3;
    const DADA_STATUS_COMPLETED = 4;
    const DADA_STATUS_CANCELLED = 5;
    const DADA_STATUS_DISPATCH_APPEND = 8;
    const DADA_STATUS_DELIVERY_BACK = 9;
    const DADA_STATUS_DELIVERY_BACK_COMPLETED = 10;
    const DADA_STATUS_AFTERSALE_BACK = 6;
    const DADA_STATUS_ADD_ORDER_FAIL = 1000;

    public static function getDadaStatusStr()
    {
        return [
            self::DADA_STATUS_DISPATCH => '待接单',
            self::DADA_STATUS_PICKUPING => '待取货',
            self::DADA_STATUS_RIDERARRIVE => '骑士到店',
            self::DADA_STATUS_DELIVERY => '配送中',
            self::DADA_STATUS_COMPLETED => '已完成',
            self::DADA_STATUS_CANCELLED => '已取消',
            self::DADA_STATUS_DISPATCH_APPEND => '已追加待接单',
            self::DADA_STATUS_DELIVERY_BACK => '妥投异常之物品返回中',
            self::DADA_STATUS_DELIVERY_BACK_COMPLETED => '妥投异常之物品返回完成',
            self::DADA_STATUS_AFTERSALE_BACK => '售后取件单送达门店',
            self::DADA_STATUS_ADD_ORDER_FAIL => '创建达达运单失败',
        ];
    }
    public static function getDadaStatusConver()
    {
        return [
            self::DADA_STATUS_DISPATCH => 20,
            self::DADA_STATUS_PICKUPING => 30,
            self::DADA_STATUS_DELIVERY => 40,
            self::DADA_STATUS_COMPLETED => 50,
            self::DADA_STATUS_CANCELLED => 60,
            self::DADA_STATUS_RIDERARRIVE => 100,
            self::DADA_STATUS_DISPATCH_APPEND => 101,
            self::DADA_STATUS_DELIVERY_BACK => 102,
            self::DADA_STATUS_DELIVERY_BACK_COMPLETED => 103,
            self::DADA_STATUS_AFTERSALE_BACK => 104,
            self::DADA_STATUS_ADD_ORDER_FAIL => 105,
        ];
    }

    const CUSTOMER_CANCEL_DEFAULT = 0;
    const CUSTOMER_CANCEL_REASON = 1;
    const MERCHANT_CANCEL_REASON = 2;
    const DELIVERY_CANCEL_REASON = 3;
    const SYSTEM_CANCEL_REASON = 10;
    public static function getCancelReasonStr()
    {
        return [
            self::CUSTOMER_CANCEL_DEFAULT => '默认值',
            self::CUSTOMER_CANCEL_REASON => '客户发起取消',
            self::MERCHANT_CANCEL_REASON => '商家发起取消',
            self::DELIVERY_CANCEL_REASON => '闪送员发起取消',
            self::SYSTEM_CANCEL_REASON => '系统自动发起取消',
        ];
    }
    const DADA_DELIVERY_CANCEL_DEFAULT = 0;
    const DADA_DELIVERY_CANCEL_REASON = 1;
    const DADA_MERCHANT_CANCEL_REASON = 2;
    const DADA_SYSTEM_CANCEL_REASON = 3;
    public static function getDadaCancelReasonStr()
    {
        return [
            self::DADA_DELIVERY_CANCEL_DEFAULT => '默认值',
            self::DADA_DELIVERY_CANCEL_REASON => '闪送员发起取消',
            self::DADA_MERCHANT_CANCEL_REASON => '商家发起取消',
            self::DADA_SYSTEM_CANCEL_REASON => '系统自动发起取消',
        ];
    }
    public static function getDadaCancelReasonConver()
    {
        return [
            self::DADA_DELIVERY_CANCEL_DEFAULT => 0,
            self::DADA_DELIVERY_CANCEL_REASON => 3,
            self::DADA_MERCHANT_CANCEL_REASON => 2,
            self::DADA_SYSTEM_CANCEL_REASON => 10,
        ];
    }
    /**
     * 订单新增
     */
    public function orderCreate($param)
    {

        // 验证数据
        try {
            validate([
                'appid'  => 'require', 
                'third_number'  => 'require', 
            ])->message([
                'appid.require'  => 'appid必须传递',   
                'third_number.require'  => 'third_number必须传递',   
                'app_type.require'  => 'app_type必须传递',   
            ])->check($param);
        } catch (ValidateException $e) {
            return result_error($e->getError());
        }
        
        $data['appid'] = $param['appid'] ?? '';//appid
        $data['third_number'] = $param['third_number'] ?? '';//配送平台订单号
        $data['sys_number'] =get_order_num($param['app_type']);//骑手系统订单号(系统生成)
        $data['call_number'] = $param['call_number'] ?? '';//调用方订单号
        $data['app_type'] = $param['app_type'] ?? 0;//第三方平台类型 1:闪送, 2:达达,3:蜂鸟
        $data['appoint_type'] = $param['appoint_type'] ?? 0;//0:立即单, 1:预约单
        $data['appointment_date'] = $param['appointment_date'] ?? '';//预约时间
        $data['store_id'] = $param['store_id'] ?? 0;//配送店铺ID
        $data['total_distance'] = $param['total_distance'] ?? 0;//总距离，单位：米
        $data['total_weight'] = $param['total_weight'] ?? 0;//总重量，单位：kg
        $data['total_amount'] = $param['total_amount'] ?? 0;//订单总金额，单位：分
        $data['coupon_save_fee'] = $param['coupon_save_fee'] ?? 0;//优惠的总额度，单位：分
        $data['dynamic_subsidy_amount'] = $param['dynamic_subsidy_amount'] ?? 0;//限时补贴的费用，单位：分
        $data['addition_amount'] = $param['addition_amount'] ?? 0;//订单加价金额，单位：分
        $data['total_fee_after_save'] = $param['total_fee_after_save'] ?? 0;//实际支付的费用，单位：分
        $data['expect_receive_time'] = $param['expect_receive_time'] ?? 0;//期望收件时间，单位：秒
        $data['estimate_grab_second'] = $param['estimate_grab_second'] ?? 0;//预计接单时长，单位：秒
        $data['estimate_receive_second'] = $param['estimate_receive_second'] ?? 0;//预计完单时长，单位：秒
        $data['status'] = $param['status'] ?? 0;//20:派单中,30:待取货,40:配送中,50:已完成,60:已取消 
        $data['deduct_amount'] = $param['deduct_amount'] ?? 0;//扣款金额，单位：分

        // 创建
        try {
            $result = $this->save($data);

            if ($result) {
                return result_success('success', $data);
            } else {
                return result_error('保存失败');
            }
        } catch (\Exception $e) {
            return result_error($e->getMessage());
        }
    }


    /**
     * 订单更新
     */
    public function orderUpdate($param)
    {
        if (empty($param['third_number'])&&empty($param['sys_number'])&&empty($param['call_number'])&&empty($param['id'])){
                return  result_error('缺少必要更新条件');
        }

        if(isset($param['appoint_type'])) $data['appoint_type'] = $param['appoint_type'];//0:立即单, 1:预约单
        if(isset($param['appointment_date'])) $data['appointment_date'] = $param['appointment_date'];//预约时间
        if(isset($param['status'])) $data['status'] = $param['status'];//0:派单中,30:待取货,40:配送中,50:已完成,60:已取消


        if(isset($param['abort_type'])) $data['abort_type'] = $param['abort_type'];//取消发起人类型 1:客户发起取消,3:闪送员发起取消,10:系统自动发起取消
        if(isset($param['punish_type'])) $data['punish_type'] = $param['punish_type'];//取消责任人类型 1:因客户,2:因服务,3:因闪送员,10:因系统自动取消,99:因其它
        if(isset($param['abort_info'])) $data['abort_info'] = $param['abort_info'];//取消订单相关信息
        if(isset($param['abort_reason'])) $data['abort_reason'] = $param['abort_reason'];//取消原因
        if(isset($param['send_back_fee'])) $data['send_back_fee'] = $param['send_back_fee'];//送回费，单位：分
        if(isset($param['drawback'])) $data['drawback'] = $param['drawback'];//退款金额，单位：分


        try {
           
            $find = $this
                    ->when(!empty($param['third_number']),function ($query) use($param) {
                        $query->where('third_number', $param['third_number']);
                    })
                    ->when(!empty($param['sys_number']),function ($query) use($param) {
                        $query->where('sys_number', $param['sys_number']);
                    })
                    ->when(!empty($param['call_number']),function ($query) use($param) {
                        $query->where('call_number', $param['call_number']);
                    })
                    ->when(!empty($param['id']),function ($query) use($param) {
                        $query->where('id', $param['id']);
                    })
                    ->find();
            if (!$find){
                 return  result_error('未查询到订单');
            }  
            
            $result=$find->save($data);

            if ($result) {
               return result_success('success',$find);
            } else {
               return result_error('保存失败');
            }
        } catch (\Exception $e) {
             return result_error($e->getMessage());
        }
    }


    /**
     * 订单加价
     */
    public function additionSave($param)
    {
        if (empty($param['third_number'])&&empty($param['sys_number'])&&empty($param['call_number'])&&empty($param['id'])){
                return  result_error('缺少必要更新条件');
        }

        try {
            validate([
                'addition_amount'  => 'require', //加价的金额（分）
            ])->message([
                'addition_amount.require'  => 'addition_amount必须传递',    
            ])->check($param);
        } catch (ValidateException $e) {
            return result_error($e->getError());
        }

        // 创建
        try {
              $find = $this
                    ->when(isset($param['third_number']),function ($query) use($param) {
                        $query->where('third_number', $param['third_number']);
                    })
                    ->when(isset($param['sys_number']),function ($query) use($param) {
                        $query->where('sys_number', $param['sys_number']);
                    })
                    ->when(isset($param['call_number']),function ($query) use($param) {
                        $query->where('call_number', $param['call_number']);
                    })
                    ->when(isset($param['id']),function ($query) use($param) {
                        $query->where('id', $param['id']);
                    })
                    ->find();
            if (!$find){
                 return  result_error('未查询到订单');
            }  

            $result=$find
                    ->setInc('total_amount', $param['addition_amount'])
                    ->setInc('total_fee_after_save', $param['addition_amount'])
                    ->setInc('addition_amount', $param['addition_amount']);

            if ($result) {
                return result_success('success',$result);
            } else {
                return result_error('保存失败');
            }
        } catch (\Exception $e) {
             return result_error($e->getMessage());
        }
    }
}